# Django settings for connie2_django project.
import os, os.path

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# This is the basis of the entire site:
URL_ROOT = '/connie2'

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

# DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
# DATABASE_NAME = 'conniegis'    # Or path to database file if using sqlite3.
# DATABASE_USER = 'connie'       # Not used with sqlite3.
# DATABASE_PASSWORD = 'connie'   # Not used with sqlite3.
# DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
# DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Australia/Hobart'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-gb'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds static files.  They will
# be written here by ./manage.py collectfiles (for staticfiles /
# pipeline); don't put anything here manually.  Example:
# "/home/media/media.lawrence.com/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, os.pardir, 'static')

# URL that handles the media served from STATIC_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
STATIC_URL = URL_ROOT + '/static/'

# Where non-app-specific files are located:
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, os.pardir, 'staticmedia'),
)

# see django-pipeline.
STATICFILES_STORAGE = "pipeline.storage.PipelineCachedStorage"

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = STATIC_URL + 'adminmedia/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = '@nh5y%%g_yvt__iuy@#1$1sora(j2lu^*vz11d(#lun+9@nnx8'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

# There is an experimental crawler from the ICT Centre using
# reverse-proxy logs to crawl dynamic content... which is kicking off
# connie runs.  Since /robots.txt is not under our control... ban them
# with CommonMiddleware (the culprit is
# http://www.atnf.csiro.au/computing/software/arch/):
import re
DISALLOWED_USER_AGENTS = (
    re.compile('archer', re.IGNORECASE),
)

ROOT_URLCONF = 'connie2_django.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, 'templates'),
)

INSTALLED_APPS = (
    'connie2_django.connie2',
    'connie2_django.marvlis',
    'django.contrib.admin',
    # uncomment to view docs:
    # 'django.contrib.admindocs',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'pipeline',
    'south',
)

AUTHENTICATION_BACKENDS = (
    # Our custom auth backend that allows email addresses to be used as usernames.
    'email_usernames.backends.EmailOrUsernameModelBackend', 
    # Default auth backend that handles everything else.
    'django.contrib.auth.backends.ModelBackend', 
)

# Used to serialise foreign-key data as well (ie, deep serialisation):
SERIALIZATION_MODULES = {
    'json': 'wadofstuff.django.serializers.json'
}

# Note: CONNIE_LOG_LEVEL here should be set to one of the logging module log levels:
import logging
CONNIE_LOG_LEVEL = logging.INFO

# django-pipeline file groups (compression settings etc are set in localsettings):
PIPELINE_CSS = {
    'connie_css': {
        'source_filenames': ('slimbox/slimbox2.css', 'jquery.tooltip.css', 'facebox.css', 'connie.less'),
        'output_filename': 'style.css'
        }
    }
PIPELINE_JS = {
    'connie_js': {
        # Note: not including OpenLayers, because that does funky stuff involving the script name to determine its location and add a css theme tag:
        'source_filenames': ('slimbox/slimbox2.js', 'tutorial.js', 'ternElapse.js', 'moment.min.js', 'map.js', 'jquery-validation.js', 'jquery.tooltip.js', 'jquery-dateui-monthonly.js', 'facebox.js', 'jquery.connieformgrid-0.2.js', 'connie.js'),
        'output_filename': 'connie_collect.js'
        }
    }
PIPELINE_COMPILERS = (
    'pipeline.compilers.less.LessCompiler',
)
PIPELINE_LESS_BINARY = '/usr/bin/lessc'

# email registration:
ACCOUNT_ACTIVATION_DAYS = 2
EMAIL_HOST = 'smtp.csiro.au'
EMAIL_PORT = 25
DEFAULT_FROM_EMAIL = 'connie@csiro.au' # this should be changed when we get a proper alias!

# The default invocation harness (over-ride in the local settings if
# required, otherwise this should be fine).  Should be the name of the
# callable to invoke with the input file as a string:
CONNIE_HARNESS = 'connie2_django.connie2.interact.invokeBySubprocess'


# Caching-backend setup:
CACHES = {
    'default' : {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/tmp/connie_cache',
        'TIMEOUT': 24 * 60 *60  # 1 day
    },
    # Want to override staticfiles, so a restart will clear it:
    'staticfiles': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'staticfiles-override'
    }
}

# hack; ability to add other apps locally (eg, django_extensions):
LOCAL_INSTALLED_APPS = None
# Attempt to import host-specific settings, fall back to defaults if that fails:
try:
    import socket
    HOSTNAME = socket.gethostname().lower().split('.')[0].replace('-','')
    # this seems to require absolute pathnames; I thought the default
    # level=-1 arg to __import__ obviated the need for that, but
    # apparently I'm wrong:
    stngs = __import__('connie2_django.localsettings_' + HOSTNAME)
    for key, value in stngs.__dict__['localsettings_'+HOSTNAME].__dict__.iteritems():
        if not key.startswith('__'):
            locals()[key] = value
except ImportError:
    from localsettings import *

if LOCAL_INSTALLED_APPS:
    INSTALLED_APPS += LOCAL_INSTALLED_APPS

# Set up logging after importing local settings, to give the option of
# over-riding level locally:
from modpython_logging import ApacheLogHandler
handler = ApacheLogHandler()
handler.setLevel(CONNIE_LOG_LEVEL)
logging.getLogger('').setLevel(CONNIE_LOG_LEVEL)
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(funcName)s: %(message)s')
handler.setFormatter(formatter)
logging.getLogger('').addHandler(handler)
